package com.android;

import java.io.IOException;
import java.util.ArrayList;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;

import com.android.agenda.AgendaActivity;
import com.android.agenda.ScheduleHelper;
import com.android.data.DatabaseHelper;
import com.android.entities.Category;
import com.android.entities.HistoryEntry;
import com.android.rate.EvaluationActivity;
import com.android.rate.HistoryHelper;
import com.android.search.CategoriesHelper;
import com.android.search.SearchEventsActivity;

public class HomeActivity extends BasicActivity {
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //Configure action bar font
        setFont(R.id.titleBar);
        
        //Create preference if it doesn't exist.
        SharedPreferences settings = getSharedPreferences(getString(R.string.preferences), MODE_PRIVATE);
        if (!settings.contains("configured") || !settings.getBoolean("configured", false)) {
        	
        	if (!settings.contains("hasDB") || !settings.getBoolean("hasDB", false)) {
	            //Check if database already exists and if it doesn't, creates it.
	            DatabaseHelper myDbHelper = new DatabaseHelper(this); 
	            try {
	            	myDbHelper.createDataBase();
	            } catch (IOException ioe) {
	            	throw new Error("Unable to create database");
	            }
	            myDbHelper.close();
	            
	            SharedPreferences.Editor editor = settings.edit();
	            editor.putBoolean("hasDB", true);
	            editor.commit();
        	}
        
            if (!settings.contains("userId")) {
            	//TODO: Create user id in server
            	//int userId = ServerManager.createUserId(this);
            	int userId = 10;
            	if (userId > 0) {
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putLong("userId", userId);
                    editor.putBoolean("configured", true);
                    editor.commit();
            	}        	
            }
        
        } else { 
        	updateCategories();
        	updateHistory();
        }
	}
    
    public void onClickAction(View v)
    {
        int id = v.getId ();
        switch (id) {
	        
	        case R.id.btnSearch :
	        
	        	//if (isOnline()) {
	               startActivity (new Intent(getApplicationContext(), SearchEventsActivity.class));
	        	//} else {
	        	//	noConnectionAlert("No connection");
	        	//}
	            break;
			
	        case R.id.btnAgenda :
	        	startActivity (new Intent(getApplicationContext(), AgendaActivity.class));
	        	break;
	        	
	        case R.id.btnRate :
	        	//TODO: save rates and send it when connected.
               startActivity (new Intent(getApplicationContext(), EvaluationActivity.class));
               break;
	            
			default: 
				break;
        }
    }
 
    private void updateCategories() {
    	//TODO: Get Categories from server
    	//ArrayList<Category> categories = ServerManager.getCategories(this);
    	ArrayList<Category> categories = new ArrayList<Category>();
    	CategoriesHelper cHelper = new CategoriesHelper(this);
    	
    	//Delete local categories
    	if (categories != null && categories.size() > 0) {
    		cHelper.deleteAll();
    	
        	//Insert categories from server
        	for (Category c: categories)
        		cHelper.createCategory(c);
    	
    	}
    	
    	cHelper.close();
    }
 
    private void updateHistory() {
    	ScheduleHelper sHelper = new ScheduleHelper(HomeActivity.this);
    	HistoryHelper hHelper = new HistoryHelper(HomeActivity.this);
    	//Get past Events and delete from Schedule table
    	ArrayList<HistoryEntry> oldEvents = sHelper.selectOldEvents();
    	
    	//insert events in History table to be evaluated
    	hHelper.createHistory(oldEvents);
    	
    	hHelper.close();
    	sHelper.close();
    }
}